<template>
  <div class="dashboard-container">
    <h2>{{ type === "add" ? "新增课程" : "修改课程" }}</h2>
    <div class="dashboard-text">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="150px"
        class="demo-ruleForm"
      >
        <el-form-item label="标题：" prop="title">
          <el-input
            v-model="ruleForm.title"
            placeholder="请输入标题"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="描述：" prop="introduce">
          <Tinymce
            ref="tinymceRef"
            height="50vh"
            width="50vw"
            @input="handleSetContent"
            @load="handleGetDetail"
          />
        </el-form-item>
        <el-form-item label="类别：" prop="categoryId">
          <el-cascader
            v-model="ruleForm.categoryId"
            :options="categoryList"
            :props="{
              value: 'id',
              label: 'name',
              emitPath: true,
            }"
          />
        </el-form-item>

        <el-form-item label="视频封面：" prop="cover">
          <div>
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :action="action"
              accept=".jpg, .jpeg, .JPG, .JPEG, .png, .PNG"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
            >
              <img v-if="ruleForm.cover" :src="ruleForm.cover" class="avatar" />
              <i v-else class="el-icon-plus" />
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="课程：" prop="section">
          <el-card
            v-for="(item, index) in ruleForm.section"
            :key="item.uid"
            class="box-card"
          >
            <div slot="header" class="clearfix">
              <span>
                <el-input
                  v-model="item.title"
                  :maxlength="8"
                  show-word-limit
                  placeholder="请输入视频章节标题"
                />
              </span>
              <el-button
                style="margin-left: 10px"
                type="text"
                @click="handleDelItem(item.id)"
                >删除</el-button
              >
            </div>
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :action="action"
              accept=".mp4,"
              :on-success="(response) => handleListSuccess(response, index)"
            >
              <video
                v-if="item.url"
                :src="item.url"
                autoplay
                style="width: 100%; height: 100%"
              />
              <!--              <img v-if="ruleForm.cover" :src="ruleForm.cover" class="avatar">-->
              <i v-else class="el-icon-plus" /> </el-upload
          ></el-card>

          <el-button type="text" @click="handleAddVideo">添加课程</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSaveContent">保存</el-button>
          <el-button @click="$router.back()">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="type !== 'add'" class="disabled-table">
      <h2>查看记录</h2>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f5f5' }"
      >
        <el-table-column label="用户名" prop="userInfo.username" />
        <el-table-column label="当前章节" prop="section_title" />
        <el-table-column label="时间记录(秒)" prop="duration" />
        <el-table-column label="创建时间" prop="create_time" />
        <el-table-column label="更新时间" prop="update_time" />
        <el-table-column label="操作" prop="op">
          <template slot-scope="scope">
            <el-button type="danger" @click="handleToUserDetail(scope.row)"
              >查看用户</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import {
  addQuestionnaireDetail,
  delQuestionnaireRecord,
  getQuestionnaireDetail,
  getQuestionnaireRecordList,
  updateQuestionnaireDetail,
} from "@/api/questionnaire";
import { getCategoryList } from "@/api/category";
import {
  addCourseDetail,
  getCourseDetail,
  getCourseHistoryList,
  updateCourseDetail,
} from "@/api/course";
import Tinymce from "@/components/Tinymce/index.vue";
export default {
  name: "Dashboard",
  components: { Tinymce },
  data() {
    return {
      action: process.env.VUE_APP_BASE_UPLOAD,
      ruleForm: {
        introduce: "",
        title: "",
        cover: "",
        categoryId: "",
        section: [],
      },
      categoryList: [],
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        introduce: [{ required: true, message: "请输入描述", trigger: "blur" }],
        cover: [{ required: true, message: "请选择封面", trigger: "blur" }],
        section: [
          { required: true, message: "请选择章节课程", trigger: "blur" },
        ],
        categoryId: [
          { required: true, message: "请选择类别", trigger: "blur" },
        ],
      },
      tableData: [],
      paginationConfig: {
        direction: "center", // 分页位置
        layout: "total, sizes, prev, pager, next, jumper", // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10, // 每页条数-默认10
      },
      dialogImageUrl: "",
      dialogVisible: false,
    };
  },
  computed: {
    type() {
      return this.$route.query.type;
    },
    isDisabled() {
      return this.type === "edit";
    },
  },
  created() {
    // this.handleGetDetail();
    this.handleGetRecordsList();
    this.getList();
  },
  methods: {
    handleSetContent(e) {
      this.ruleForm.introduce = e;
    },
    async handleGetDetail() {
      this.$refs.tinymceRef.setContent("");
      if (!this.$route.query.id) return;
      const res = await getCourseDetail({
        id: this.$route.query.id,
      });
      if (res.code === 200) {
        this.ruleForm = Object.assign({}, res.data);
        this.$nextTick(() => {
          this.$refs.tinymceRef.setContent(res.data?.introduce || "");
        });
      }
    },
    async handleGetRecordsList() {
      if (!this.$route.query.id) return;
      const { page, pageSize } = this.paginationConfig;
      const res = await getCourseHistoryList({
        courseId: this.$route.query.id,
        page,
        pageSize,
      });
      if (res.code === 200) {
        this.tableData = res.data;
      }
    },
    async getList() {
      const res = await getCategoryList();
      if (res.code === 200) {
        this.categoryList = res.data;
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.ruleForm.cover = "";
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(response, file, fileList) {
      if (response.code === 200) {
        file.url = response.data;
        this.ruleForm.cover = response.data;
      }
    },
    handleDelItem(id) {
      this.ruleForm.section = this.ruleForm.section.filter((v) => v.id !== id);
    },
    handleListSuccess(response, index) {
      const form = Object.assign({}, this.ruleForm);
      form.section[index].url = response.data;
      this.ruleForm = form;
    },

    handleAddVideo() {
      const form = Object.assign({}, this.ruleForm);
      form.section.push({
        url: "",
        title: "",
        id: Date.now(),
      });
      this.ruleForm = form;
    },
    handleChangePage({ page, pageSize }) {
      this.paginationConfig.page = page;
      this.paginationConfig.pageSize = pageSize;
      this.handleGetRecordsList();
    },
    handleSaveContent() {
      this.$refs.ruleForm.validate(async (valid) => {
        console.log(valid);
        if (valid) {
          if (this.type === "add") {
            const form = Object.assign({}, this.ruleForm);
            form.section = form.section.map((v) => {
              return {
                title: v.title,
                url: v.url,
                id: v.id,
              };
            });
            form.state = 1;
            const res = await addCourseDetail(form);
            if (res.code === 200) {
              this.$message.success(res.data);
              this.$router.back();
            }
          } else {
            const form = Object.assign({}, this.ruleForm);
            form.section = form.section.map((v) => {
              return {
                title: v.title,
                url: v.url,
              };
            });
            const res = await updateCourseDetail(this.ruleForm);
            if (res.code === 200) {
              this.$message.success(res.data);
              this.$router.back();
            }
          }
        }
      });
    },
    async handleDel(e) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const res = await delQuestionnaireRecord({
          id: e.id,
        });
        if (res.code === 200) {
          this.$message.success(res.data);
          this.handleGetRecordsList();
        }
      });
    },
    handleToUserDetail(e) {
      this.$router.push({
        name: "userDetail",
        query: {
          id: e.userId,
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    margin-bottom: 30px;
  }
}

.el-input,
.el-textarea {
  width: 300px;
}
.box {
}
.box-card {
  display: inline-block;
  width: 32%;
  margin-right: 1%;
  .header {
    display: flex;
    align-items: flex-start;
  }
}
.scope-box {
  .scope-item {
    margin-right: 1%;
    display: inline-block;
    width: 20%;
  }
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
}
::v-deep {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
